/*************************************************************************
 *
 * ButtonTask
 * 
 * (c) Ales Povalac, alpov@alpov.net, http://www.alpov.net/
 * 
 *************************************************************************
 *
 * $Id: button.c 39 2006-07-02 09:24:50Z alpov $
 * 
 *************************************************************************/         

#include <stdint.h>
#include <avr/io.h>
#include "../avrx/avrx.h"
#include "../avrx/AvrXFifo.h"
#include "button.h"
#include "menu.h"
#include "beep.h"

TimerControlBlock ButtonDelayTimer, BacklightTimer, ButtonRepeatTimer;


/*************************************************************************
 * inicializace tasku
 *************************************************************************/ 
void InitButtonTask(void)
{
	DDRA |= _BV(PA7);
	PORTB |= 0x0f;
	
	BackLight(1);
	BackLightTimer();
}


/*************************************************************************
 * BackLightTimer() spusti casovac, po jeho expiraci vypne ButtonTask
 * podsvetleni displeje 
 *************************************************************************/ 
void BackLightTimer(void)
{
    AvrXCancelTimer(&BacklightTimer);
    AvrXTestTimer(&BacklightTimer);
    AvrXStartTimer(&BacklightTimer, BACKLIGHT_TIMEOUT);
}


/*************************************************************************
 * uloha ButtonTask
 * min. stack 4B 
 *************************************************************************/ 
AVRX_GCC_TASKDEF(ButtonTask, 5, 2)
{
    unsigned char c;
    
    while (1) {
        AvrXDelay(&ButtonDelayTimer, BUTTON_FILTER);
        c = ReadKey(); // & 0x7f
        if (c) {
            AvrXPutFifo(MenuFifo, c);
            BackLight(1);
            
            AvrXSendMessage(&BeepQueue, &BeepStop);
            
            AvrXCancelTimer(&ButtonRepeatTimer);
            AvrXTestTimer(&ButtonRepeatTimer);
            AvrXStartTimer(&ButtonRepeatTimer, BUTTON_DELAY);
            
            while (1) {
                if (c == ReadKey()) {
                    if (AvrXTestTimer(&ButtonRepeatTimer) == SEM_DONE) {
                        AvrXPutFifo(MenuFifo, c);
                        AvrXStartTimer(&ButtonRepeatTimer, BUTTON_REPEAT);
                    }
                } else {
                    while (c) {
                        AvrXDelay(&ButtonDelayTimer, BUTTON_FILTER);
                        c = ReadKey();
                    }
                    BackLight(1);
                    BackLightTimer();

                    break;
                }
                AvrXDelay(&ButtonDelayTimer, BUTTON_FILTER);
            }

        } else {
            if (AvrXTestTimer(&BacklightTimer) == SEM_DONE) 
                BackLight(0);
        }
    }
}

